package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.service.merchant.IMerchantThirdProtocolInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.datapush.service.apipush.utils.WangXunAesUtils;
import com.block.datapush.service.apipush.utils.WangXunRsaUtils;
import com.block.datapush.service.apipush.utils.XiaoCaiDaiKuanMaskUtil;
import com.block.db.entity.*;
import com.block.db.mapper.DataMatchOrderItemMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 小财贷款 全流程掩码
 */
@Service
public class XiaoCaiDaiKuanMaskApisService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Autowired
    DataMatchOrderItemMapper dataMatchOrderItemMapper;
    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String channelCode = pushApiKeyParam.getApiCode();

        //平台方公钥
        String pubKey = pushApiKeyParam.getPubKey();
        //我方私钥
        String priKey = pushApiKeyParam.getPriKey();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobileMd5", memberSourceInfo.getMobileMd5().toLowerCase());
        bizMap.put("mobileMask", memberSourceInfo.getMobile().substring(0,9));
        bizMap.put("realName", memberSourceInfo.getRealname());
        bizMap.put("ip", XiaoCaiDaiKuanMaskUtil.getIp(memberSourceInfo.getReqIp()));
        bizMap.put("osType", "android");
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", XiaoCaiDaiKuanMaskUtil.getSex(memberSourceInfo.getSex()));
        bizMap.put("cityCode", memberSourceInfo.getCityCode());
        bizMap.put("idNo", memberSourceInfo.getIdcard());
        bizMap.put("salaryOfMonth", XiaoCaiDaiKuanMaskUtil.getShouru(memberSourceInfo.getShouru()));
        bizMap.put("education", XiaoCaiDaiKuanMaskUtil.getXueli(memberSourceInfo.getXueli()));
        bizMap.put("profession", XiaoCaiDaiKuanMaskUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("workTime", 12);
        bizMap.put("paymentForm", 0);
        bizMap.put("commercialInsurance", XiaoCaiDaiKuanMaskUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("house", XiaoCaiDaiKuanMaskUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", XiaoCaiDaiKuanMaskUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("carType", 0);
        bizMap.put("carOwnership", 0);
        bizMap.put("carState", 0);
        bizMap.put("carYear", 0);
        bizMap.put("carPrice", 0);
        bizMap.put("socialSecurity", XiaoCaiDaiKuanMaskUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("accumulationFound", XiaoCaiDaiKuanMaskUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("creditCard", XiaoCaiDaiKuanMaskUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("weili", XiaoCaiDaiKuanMaskUtil.getWeiLi(memberSourceInfo.getWeili()));
        bizMap.put("zhima", XiaoCaiDaiKuanMaskUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("loanAmount", XiaoCaiDaiKuanMaskUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", XiaoCaiDaiKuanMaskUtil.getLoanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("purpose", XiaoCaiDaiKuanMaskUtil.getYongTu(memberSourceInfo.getYongtu()));
        bizMap.put("overdue", XiaoCaiDaiKuanMaskUtil.getYuQi(memberSourceInfo.getYuqi()));
        bizMap.put("baiTiao", XiaoCaiDaiKuanMaskUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("huaBei", XiaoCaiDaiKuanMaskUtil.getHuaBei(memberSourceInfo.getHuabei()));
        bizMap.put("businessName", "无");
        bizMap.put("businessTime", 0);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        bizMap.put("createTime", LocalDateTime.now().format(formatter));
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String authUrl = StrUtil.format("{}/page/xiaocaiprotocol/{}.html", appInfoByAppCode.getApiUrl(), memberSourceInfo.getUid());
        bizMap.put("authUrl", authUrl);

        String aesKey = WangXunAesUtils.getKey();
        String key = WangXunRsaUtils.encrypt(aesKey,pubKey);
        String data1 = WangXunAesUtils.encrypt(JSON.toJSONString(bizMap),aesKey);
        String sign =WangXunRsaUtils.sign(data1,priKey);

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelId",channelCode);
        paramMap.put("data",data1);
        paramMap.put("key",key);
        paramMap.put("sign",sign);

        log.info("【小财贷款全流程】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);
        log.info("【小财贷款全流程】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        JSONObject data = resultObject.getJSONObject("data");

        pushApiResult.setCode(code+"");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals("0",String.valueOf(code))) {
            String name = data.getString("name");
            String logo = data.getString("logo");
            String userId = data.getString("userId");
            String institutionName = data.getString("orgName");
            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("orderNo",userId);
            infoObject.put("productId",userId);
            infoObject.put("productName",name);
            infoObject.put("companyName",institutionName);
            infoObject.put("companyLogo",logo);
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray protocolList = data.getJSONArray("protocols");
            for (int i=0;i<protocolList.size();i++){
                JSONObject jsonObject = new JSONObject();
                String protocolName = protocolList.getJSONObject(i).getString("label");
                String protocolUrl = protocolList.getJSONObject(i).getString("value");
                jsonObject.put("protocalName",protocolName);
                jsonObject.put("protocalUrl",protocolUrl);
                jsonArray.add(jsonObject);
            }
            infoObject.put("protocalList",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);
//            JSONArray md5List = data.getJSONArray("md5List");
//            String mobileMd5 = memberSourceInfo.getMobileMd5();
//            if (MobileMd5IsInListUtils.isMobileMd5InList(md5List, mobileMd5)) {
//                // 存在
//                pushApiResult.setCode(code + "|" + "500");
//                pushApiResult.setMessage(msg + "|" + mobileMd5 + "号码已存在");
//                pushApiResult.setPushSuccess(false);
//                return pushApiResult;
//            }

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                String price = data.getString("price");
                BigDecimal price1 = new BigDecimal(price);//下游返回分润后价格
                if (price1.compareTo(new BigDecimal(0.00)) == -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceLeft = price1.divide(typeRate);//分润前价格
                pushApiResult.setPrice(priceLeft);
                pushApiResult.setPriceRight(price1);
            }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);
                extJson.put("userId", userId);
            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        String userId = extJson.getString("userId");
        //平台方公钥
        String pubKey = pushApiKeyParam.getPubKey();
        //我方私钥
        String priKey = pushApiKeyParam.getPriKey();
        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String channelCode = pushApiKeyParam.getApiCode();
        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("id", userId);
        bizMap.put("mobile", memberSourceInfo.getMobile());
        bizMap.put("realName", memberSourceInfo.getRealname());
        bizMap.put("ip", XiaoCaiDaiKuanMaskUtil.getIp(memberSourceInfo.getReqIp()));
        bizMap.put("osType", "android");
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", XiaoCaiDaiKuanMaskUtil.getSex(memberSourceInfo.getSex()));
        bizMap.put("cityCode", memberSourceInfo.getCityCode());
        bizMap.put("idNo", memberSourceInfo.getIdcard());
        bizMap.put("salaryOfMonth", XiaoCaiDaiKuanMaskUtil.getShouru(memberSourceInfo.getShouru()));
        bizMap.put("education", XiaoCaiDaiKuanMaskUtil.getXueli(memberSourceInfo.getXueli()));
        bizMap.put("profession", XiaoCaiDaiKuanMaskUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("workTime", 12);
        bizMap.put("paymentForm", 0);
        bizMap.put("commercialInsurance", XiaoCaiDaiKuanMaskUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("house", XiaoCaiDaiKuanMaskUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", XiaoCaiDaiKuanMaskUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("carType", 0);
        bizMap.put("carOwnership", 0);
        bizMap.put("carState", 0);
        bizMap.put("carYear", 0);
        bizMap.put("carPrice", 0);
        bizMap.put("socialSecurity", XiaoCaiDaiKuanMaskUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("accumulationFound", XiaoCaiDaiKuanMaskUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("creditCard", XiaoCaiDaiKuanMaskUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("weili", XiaoCaiDaiKuanMaskUtil.getWeiLi(memberSourceInfo.getWeili()));
        bizMap.put("zhima", XiaoCaiDaiKuanMaskUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("loanAmount", XiaoCaiDaiKuanMaskUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", XiaoCaiDaiKuanMaskUtil.getLoanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("purpose", XiaoCaiDaiKuanMaskUtil.getYongTu(memberSourceInfo.getYongtu()));
        bizMap.put("overdue", XiaoCaiDaiKuanMaskUtil.getYuQi(memberSourceInfo.getYuqi()));
        bizMap.put("baiTiao", XiaoCaiDaiKuanMaskUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("huaBei", XiaoCaiDaiKuanMaskUtil.getHuaBei(memberSourceInfo.getHuabei()));
        bizMap.put("businessName", "无");
        bizMap.put("businessTime", "0");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        bizMap.put("createTime", LocalDateTime.now().format(formatter));

        String orderId = extJson.getString("orderId");
        String orderItemId = extJson.getString("orderItemId");
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), orderId, orderItemId);
        bizMap.put("authUrl", protocolUrl);

        String aesKey = WangXunAesUtils.getKey();
        String key = WangXunRsaUtils.encrypt(aesKey,pubKey);
        String data1 = WangXunAesUtils.encrypt(JSON.toJSONString(bizMap),aesKey);
        String sign =WangXunRsaUtils.sign(data1,priKey);

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelId",channelCode);
        paramMap.put("data",data1);
        paramMap.put("key",key);
        paramMap.put("sign",sign);

        log.info("【小财贷款全流程】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);


        log.info("【小财贷款全流程】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        Boolean ok = resultObject.getBoolean("ok");

        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 0 && ok) {
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);

        if (code == 0 && ok) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }


    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
